﻿using System;
using System.Linq;
using System.Linq.Expressions;

namespace LambdaManAi
{
    public class ProcessorPrint : IProcessor
    {
        private readonly LambdaManAICompiler _compiler = new LambdaManAICompiler();

        public object ProcessCode(string functionName, Expression<Func<object>> expression)
        {
            _compiler.CreateFunction(functionName, expression.Body);
            return null;
        }

        public object ProcessCode(string functionName, Locals locals, Expression<Func<object>> expression)
        {
            if (locals == null || locals.Count == 0)
                return ProcessCode(functionName, expression);

            int minKey = locals.Keys.Min();
            int maxKey = locals.Keys.Max();
            
            if (locals.Keys.Count != maxKey - minKey + 1)
                throw new Exception("Locals should have successive numbers.");

            for (int key = minKey; key <= maxKey; key++)
            {
                string currentFunctionName = key == minKey ? functionName : functionName + "_with_local_" + (key - 1);
                string nextFunctionName = functionName + "_with_local_" + key;
                _compiler.CreateExtenderFunction(currentFunctionName, nextFunctionName, key, locals.GetExpression(key).Body);
            }

            string lastFunctionName = functionName + "_with_local_" + maxKey; 
            _compiler.CreateFunction(lastFunctionName, expression.Body);

            return null;
        }
    }
}